﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Pavilion
{
    internal class PolygonAndMultiLineIntersection
    {
        private MultiLineCollisionData multiLineCollisionData;
        private PolygonCollisionData polygonCollisionData;
        private PolygonPhysicalData PolygonData { get { return multiLineCollisionData.PhysicalData as PolygonPhysicalData; } }
        private MultiLinePhysicalData MultiLineData { get { return polygonCollisionData.PhysicalData as MultiLinePhysicalData; } }
        private bool checkIntersection;

        public PolygonAndMultiLineIntersection(MultiLineCollisionData multiLineCollisionData, PolygonCollisionData polygonCollisionData)
        {
            this.checkIntersection = true;
            this.multiLineCollisionData = multiLineCollisionData;
            this.polygonCollisionData = polygonCollisionData;

            PolygonData.PhysicalFormChanged += new Action<PhysicalData>(PhysicalData_PhysicalFormChanged);
            MultiLineData.PhysicalFormChanged += new Action<PhysicalData>(PhysicalData_PhysicalFormChanged);
        }

        internal void UpdateIntersection()
        {
            if (!checkIntersection)
                return;

            checkIntersection = false;
            bool intersected = false;

            foreach (List<Vector2> lineSequence in MultiLineData.LineSequenceCollection)
            {
                for (int i = 1; i < lineSequence.Count; i++)
                {
                    LineVector line = new LineVector(lineSequence[i - 1], lineSequence[i] - lineSequence[i - 1]);

                   // Logger.WriteLine("Player", "Checking Interesection of Line: " + line + " against Ploygon: " + PolygonData.PhysicalBounds);

                    if (LineVector.Intersects(PolygonData.PhysicalBounds, line))
                    {   
                        multiLineCollisionData.AddLine(line);
                        intersected = true;
                       // Logger.WriteLine("Player", "    - Interesected");
                    }
                    else
                    {
                        multiLineCollisionData.RemoveLine(line);
                      //  Logger.WriteLine("Player", "    - NOT Interesected");
                    }
                }
            }

            if (intersected)
                polygonCollisionData.AddPolygon(PolygonData);
            else
                polygonCollisionData.RemovePolygon(PolygonData);
        }

        private void PhysicalData_PhysicalFormChanged(PhysicalData physicalData) { checkIntersection = true; }
    }
}
